<template>
  <div>
    <Card  :bordered="false"  dis-hover>
      <Form ref="searchForm"  layout="inline"    @keydown.enter.native="search" >
        <Row   :gutter="48" >
          <Col :md="8" :sm="24" >
            <FormItem label ="账户"  label-for	="account"  :label-width="45" >
              <Input   type="text"  v-model="queryParam.account" placeholder="请输入账户" />
            </FormItem>
          </Col>
          <Col :md="8" :sm="24"  >
            <FormItem label ="状态" label-for	="status"   :label-width="45" placeholder="请选择状态">
              <Select v-model="queryParam.status"  >
                <Option  value ="1">启用</Option>
                <Option  value ="2">冻结</Option>
              </Select>
            </FormItem>
          </Col>


          <template v-if="advanced">
            <Col  :md="8" :sm="24" >
              <FormItem label ="姓名"  label-for	="name"  :label-width="45" >
                <Input   type="text"  v-model="queryParam.name" placeholder="请输入姓名" />
              </FormItem>
            </Col>

            <Col  :md="8" :sm="24" >
              <FormItem label ="部门"  label-for	="deptid"  :label-width="45" >
                <Select  v-model="queryParam.deptid" ref="select">
                  <i-option v-for="item of list" :value="item.value" :key="item.value" style="display: none;">
                    {{ item.name }}
                  </i-option>
                  <Tree :data="loadData"  ref="deptTree"  @on-select-change="handleCheckChange" :show-checkbox="false" :multiple="false" ></Tree>
                </Select>
              </FormItem>
            </Col>
            <Col :md="8" :sm="24"  >
              <FormItem label ="电话"  label-for	="phone"  :label-width="45" >
                <Input   type="text"  v-model="queryParam.phone" placeholder="请输入电话" />
              </FormItem>
            </Col>
            <Col :md="8" :sm="24" >
              <FormItem label ="邮箱"  label-for	="email"  :label-width="45" >
                <Input   type="text"  v-model="queryParam.email" placeholder="请输入邮箱" />
              </FormItem>
            </Col>

          </template>
          <Col :md="!advanced && 8 || 24" :sm="24">
            <span  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <Button type="primary" @click="search">查询</Button>
              <Button style="margin-left: 8px" @click="reset">重置</Button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </Col>
        </Row>
      </Form>


      <div class="table-operator" ref="operator">
        <Button type="primary"    @click="$refs.createModal.add()">新建</Button>
        <Button   type="default"   style="margin-left: 8px;"    @click="search">刷新</Button>
          <Button type="dashed"  style="margin-left: 8px;"   @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }} alert</Button>
        <Dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <DropdownMenu slot="overlay">
            <DropdownItem key="1"><a-icon type="delete" />删除</DropdownItem>
            <!-- lock | unlock -->
            <DropdownItem key="2"><a-icon type="lock" />锁定</DropdownItem>
          </DropdownMenu>
          <Button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </Button>
        </Dropdown>

        <div style="padding: 21px 0px;margin-bottom: -21px;">
          <Row>
            <Alert v-if="optionAlertShow" style="height:40px" show-icon>已选择
              <span class="select-count">{{this.selectedRows.length}}</span>
              项
              <span class="clear-text " @click="() => { this.selectedRows = []; this.$refs.userTable.selectAll(false) } " >清空</span>
            </Alert>
          </Row>
        </div>


      </div>

      <Table ref="userTable"   stripe    border :loading="loading"    @on-selection-change="selectedAll"      :data="tableData" :columns="columns">
          <template slot-scope="{ row, index }" slot="action">
                <a  @click="$refs.editModal.edit(row)">修改</a>
                <Divider type="vertical" />
                <a  @click="freeze(row)"  v-show="row.status ===1">冻结 <Divider type="vertical" /></a>
                <a  @click="freeze(row)"  v-show="row.status ===2">解除冻结  <Divider  type="vertical"/></a>
                <a  @click="$refs.roleModal.open(row)">分配角色</a>
                <Divider type="vertical" />
                <a  @click="resetPassword(row)">重置密码</a>


          </template>

        <span slot="status" slot-scope="{row,index}">
           <Badge  :status="row.status | statusTypeFilter" :text="row.status | statusFilter" />
        </span>
      </Table>


      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
          <Page :current="currentIndex"    :total="totals" :page-size="pageSize" show-total class="paging" @on-change="changepage" @on-page-size-change="pages" show-sizer show-elevator show-total></Page>
        </div>
      </div>

    </Card>


    <user-add ref="createModal" @ok="handleOk" />
    <user-edit ref="editModal" @ok="handleOk" />
    <user-role ref="roleModal" @ok="handleOk" />
  </div>






</template>
<script>
    import {formatLocalDate} from '@/libs/formatDate'
    import  UserAdd from  './modules/UserAdd.vue';
    import UserEdit  from "./modules/UserEdit.vue";
    import UserRole  from "./modules/UserRole.vue";
    import {getUserList,freezeUser,getDeptTree,resetPassword} from '@/api/userList'

    const statusMap = {
        1: {
            status: 'success',
            text: '启用'
        },
        2: {
            status: 'error',
            text: '冻结'
        }
    }



    export default {
        name: 'usermgt',
        components:{
            UserAdd,
            UserEdit,
            UserRole,
        },
        data () {
            return {
                // 高级搜索 展开/关闭
                advanced: false,
                // 查询参数
                queryParam: {},
                selectedRowKeys: [],
                selectedRows: [],
                optionAlertShow: false,
                loading:true,
                totals:0,
                pageSize:20,
                currentIndex:1,
                list:[],
                loadData:[],
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                        title:'',
                    },
                    { title: '账号', key: 'account',align:"center" },
                    { title: '姓名', key: 'name',align:"center" },
                    { title: '性别', key: 'sex',align:"center",render: (h,params)=>{
                           let sex = '';
                           if(params.row.sex ===1){
                               sex=  '男';
                           }else{
                               sex=  '女';
                           }
                            return h('span',
                                sex
                            )
                        }},
                    { title: '邮箱', key: 'email',align:"center" },
                    { title: '电话', key: 'phone' ,align:"center"},
                    { title: '角色', key: 'roleName' ,align:"center"},
                    { title: '部门', key: 'deptName' ,align:"center"},
                    { title: '状态', key: 'status',align:"center", slot:"status",/*render: (h,params,vm)=>{
                            let status = '';
                            if(params.row.status ===1){
                                status=  '启用';
                            }else if(params.row.status ===2){
                                status=  '冻结';
                            }else{
                                status=  '删除';
                            }
                            return h('span',
                                status
                            )
                        }*/},
                    {
                                title: '操作',
                                key: 'action',
                                align:"center",
                                slot: 'action',
                                width: 275,

                    }
                ],
                tableData: [],
            }
        },
        filters: {
            statusFilter (type) {
                return statusMap[type].text
            },
            statusTypeFilter (type) {
                return statusMap[type].status
            }
        },
        created () {
            this.tableOption()
            //getRoleList({ t: new Date() })
        },
        methods: {
            handleCheckChange (data) {
                let value = ''
                let name = ''
                this.list = []
                data.forEach((item, index) => {

                    value =`${item.id}`
                    name = `${item.name}`

                })
                this.list.push({
                    value,
                    name
                })
                this.queryParam.deptid = value;
                this.$refs.operator.click();
            },

            tableOption () {
                if (!this.optionAlertShow) {
                    this.optionAlertShow = true
                } else {
                    this.optionAlertShow = false
                }
            },
            getData(){
                let offset  = (this.currentIndex - 1) * this.pageSize;
                this.queryParam.limit= this.pageSize;
                this.queryParam.offset= offset;
                let that = this;
                getUserList(this.queryParam).then(function (response) {
                    that.tableData = response.data.data.rows;
                    that.totals= response.data.data.total;
                    that.loading = false;
                }).catch(function (error) {
                    that.loading = false;
                });
            },
            changepage(index){
                this.currentIndex = index;
                this.getData();
            },
            pages(num){
                this.pageSize = num;
                this.currentIndex= 1
                this.getData();
            },
            search(){
                this.loading=true;
                this.currentIndex= 1
                this.getData();
            },
            reset(){
                this.queryParam = {}
                let  node =  this.$refs.deptTree.getSelectedNodes();
                node.forEach((item) => {
                    item.selected = false;
                });
                let arr = this.$refs.deptTree.stateTree;
                arr.forEach((item)=>{
                    item.expand = false;
                });
            },
            freeze(row){
                  let statu = row.status;
                  let title = '';
                  let content = '';
                  let resultMessage = '';
                  if(statu ===1){
                      title = '冻结';
                      content = '<p>是否确认冻结该账户</p>';
                      resultMessage = '用户已冻结';
                  }else if(statu ===2){
                      title = '解除冻结';
                      content = '<p>是否确认解除冻结该账户</p>';
                      resultMessage = '用户已解除冻结';
                  }
                this.$Modal.confirm({
                    title:   title,
                    content: content,
                    onOk: () => {
                        let userInfo = {};
                        userInfo.id= row.id;
                        userInfo.status = row.status;
                        freezeUser(userInfo).then(res=>{
                             if(res.data.code ===200){
                                 this.$Message.success({
                                     content:resultMessage,
                                     duration: 3,
                                     closable: true
                                 });
                                 //刷新页面列表
                                 this.handleOk();
                             }else{
                                 this.$Message.success({
                                     content:res.data.message,
                                     duration: 3,
                                     closable: true
                                 });
                             }
                        }).catch(function (error) {
                            console.log(error+"冻结失败！！！")
                        })
                    },
                    onCancel: () => {
                       console.log("用户取消了冻结账户！！！")
                    }
                });
            },

            toggleAdvanced () {
                this.advanced = !this.advanced
            },
            selectedAll () {
                let selectedRow = this.$refs.userTable.getSelection();

                //this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRow
            },
            handleOk(){
                this.search();
            },
            resetPassword(row){
                this.$Modal.confirm({
                    title: '是否重置密码',
                    content: '密码将重置为111111',
                    onOk: () => {
                        let userInfo = {};
                        userInfo.userId = row.id;
                        resetPassword(userInfo).then(res=>{
                            if(res.data.code ===200){
                                this.$Message.success({
                                    content:'重置成功',
                                    duration: 3,
                                    closable: true
                                });
                                //刷新页面列表
                                this.handleOk();
                            }else{
                                this.$Message.success({
                                    content:res.data.message,
                                    duration: 3,
                                    closable: true
                                });
                            }
                        }).catch(function (error) {
                            console.log(error+"重置密码失败！！！")
                        })
                    },
                    onCancel: () => {
                        console.log("用户取消了重置密码！！！")
                    }
                });
            }
        },
        mounted () {
              this.getData();
              getDeptTree()
                  .then(res => {
                      this.loadData =  res.data;
                  }).catch(function (error) {
                  console.log(error+"用户部门树加载失败");
              })
        }

    }
</script>

<style lang="less">
  @import 'index.less';

  .paging {
    float: left;
    margin-top: 10px;
  }

 .table-operator{
   padding: 5px 5px 15px 0px;


 }
</style>
